package com.qlslylq.ad.sdk.core.loader;

import android.app.Activity;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdLoadType;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTFullScreenVideoAd;
import com.kwad.sdk.api.KsFullScreenVideoAd;
import com.kwad.sdk.api.KsLoadManager;
import com.kwad.sdk.api.KsScene;
import com.kwad.sdk.api.KsVideoPlayConfig;
import com.kwad.sdk.api.SdkConfig;
import com.mbridge.msdk.out.MBRewardVideoHandler;
import com.mbridge.msdk.out.MBridgeIds;
import com.mbridge.msdk.out.RewardInfo;
import com.mbridge.msdk.out.RewardVideoListener;
import com.qlslylq.ad.sdk.config.CsjMgrHolder;
import com.qlslylq.ad.sdk.config.KsMgrHolder;
import com.qlslylq.ad.sdk.constant.AppConst;
import com.qlslylq.ad.sdk.constant.UrlConst;
import com.qlslylq.ad.sdk.core.ad.BaseAd;
import com.qlslylq.ad.sdk.core.interceptor.RewardVideoADListener;
import com.qlslylq.ad.sdk.core.interceptor.WindInterstitialAdListener;
import com.qlslylq.ad.sdk.core.listener.FullScreenAdListener;
import com.qlslylq.ad.sdk.core.mgr.PoolMgr;
import com.qlslylq.ad.sdk.core.rsp.AdError;
import com.qlslylq.ad.sdk.enums.AdEventSign;
import com.qlslylq.ad.sdk.enums.AdPlatformEnum;
import com.qlslylq.ad.sdk.enums.ErrorEnum;
import com.qlslylq.ad.sdk.model.req.UserBehaviorAddDTO;
import com.qlslylq.ad.sdk.model.rsp.AdPlaceWebConfigureVO;
import com.qlslylq.ad.sdk.net.api.ApiServiceImpl;
import com.qlslylq.ad.sdk.util.DecimalUtils;
import com.qlslylq.ad.sdk.util.GsonUtils;
import com.qlslylq.ad.sdk.util.Log;
import com.qq.e.ads.rewardvideo.RewardVideoAD;
import com.sigmob.windad.WindAdError;
import com.sigmob.windad.interstitial.WindInterstitialAd;
import com.sigmob.windad.interstitial.WindInterstitialAdRequest;

import java.util.List;
import java.util.Map;

import static com.qlslylq.ad.sdk.enums.OrientationEnum.LANDSCAPE;
import static com.qlslylq.ad.sdk.enums.OrientationEnum.PORTRAIT;

/**
 * 全屏视频广告加载器<br/>
 */
public class FullScreenAdLoader extends AdLoader<FullScreenAdListener> {

    public FullScreenAdLoader(Activity context, long posId, FullScreenAdListener adListener) {
        super(context, posId, adListener);
    }

    /**
     * 加载并展示<br/>
     */
    protected void load(AdPlaceWebConfigureVO config) {
        AdPlatformEnum platform = config.getPlatform();
        String posId = config.getPositionId();

        if (platform == AdPlatformEnum.PLATFORM_CSJ) {//穿山甲
            AdSlot adSlot = new AdSlot.Builder()
                    .setCodeId(posId)
                    .setOrientation(orientation == PORTRAIT ? TTAdConstant.VERTICAL : TTAdConstant.HORIZONTAL)//方向由创建时决定，且不能改变，此处应可省
                    .setExpressViewAcceptedSize(AppConst.CSJ_VIDEO_SIZE, AppConst.CSJ_VIDEO_SIZE)//只要设置的值大于0即可
                    .setAdLoadType(TTAdLoadType.PRELOAD)//[实时加载，预加载]
                    .setSupportDeepLink(true)//?
                    .build();
            CsjMgrHolder.createAdNative(context).loadFullScreenVideoAd(adSlot, new TTAdNative.FullScreenVideoAdListener() {
                @Deprecated
                public void onFullScreenVideoCached() {

                }

                public void onFullScreenVideoCached(TTFullScreenVideoAd ad) {

                }

                public void onFullScreenVideoAdLoad(TTFullScreenVideoAd ad) {
                    PoolMgr.getInstance().push(ad, config);

                    getAdListener().onAdLoad();

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_RETURN_SUCCESS, FullScreenAdLoader.super.posId));
                }

                public void onError(int code, String msg) {
                    Log.e(GsonUtils.gsonString(AdError.build(platform, adType, code, msg)));
                    getAdListener().onAdLoadError(AdError.build(platform, adType, code, msg));

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_RETURN_FAIL, FullScreenAdLoader.super.posId));
                }
            });

        } else if (platform == AdPlatformEnum.PLATFORM_YLH) {//优量汇(没有全屏广告，代替使用激励广告。即在聚合平台全屏广告位中优量汇中直接使用激励的广告位ID，但应该有重复绑定的错误)
            PoolMgr.getInstance().push(new Object(), config);
        } else if (platform == AdPlatformEnum.PLATFORM_KS) {//快手联盟
            KsScene scene = new KsScene.Builder(DecimalUtils.parseLongSafe(posId))
                    .setBackUrl(UrlConst.BACK_URL_AD) // scheme逆向唤醒协议名设置，与清单中所注册的协议名保持一致即可
                    .screenOrientation(orientation == PORTRAIT ? SdkConfig.SCREEN_ORIENTATION_PORTRAIT : SdkConfig.SCREEN_ORIENTATION_LANDSCAPE)//不起决定性
                    .build();
            KsMgrHolder.get().loadFullScreenVideoAd(scene, new KsLoadManager.FullScreenVideoAdListener() {
                public void onFullScreenVideoAdLoad(List<KsFullScreenVideoAd> list) {
                    try {
                        KsFullScreenVideoAd ad = list.get(0);

                        PoolMgr.getInstance().push(ad, config);

                        getAdListener().onAdLoad();
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.e(GsonUtils.gsonString(ErrorEnum.ERR_NO_AD.rsp(platform, adType)));
                        getAdListener().onAdLoadError(ErrorEnum.ERR_NO_AD.rsp(platform, adType));
                    }

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_RETURN_SUCCESS, FullScreenAdLoader.super.posId));
                }

                public void onRequestResult(int adNumber) {

                }

                public void onError(int code, String msg) {
                    Log.e(GsonUtils.gsonString(AdError.build(platform, adType, code, msg)));
                    getAdListener().onAdLoadError(AdError.build(platform, adType, code, msg));

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_RETURN_FAIL, FullScreenAdLoader.super.posId));
                }
            });
        } else if (platform == AdPlatformEnum.PLATFORM_SIGMOB) {//SigMob的插屏广告位最好是配置到全屏广告位中
            WindInterstitialAdRequest request = new WindInterstitialAdRequest(posId, null, null);
            WindInterstitialAdListener listener = new WindInterstitialAdListener() {

                public void onInterstitialAdPreLoadSuccess(String placementId) {

                }

                public void onInterstitialAdPreLoadFail(String placementId) {

                }

                public void onInterstitialAdLoadSuccess(String placementId) {
                    PoolMgr.getInstance().push(getAd(), config);

                    getAdListener().onAdLoad();

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_RETURN_SUCCESS, FullScreenAdLoader.super.posId));
                }

                public void onInterstitialAdPlayStart(String placementId) {
                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_EXPOSURE, FullScreenAdLoader.super.posId));
                }

                public void onInterstitialAdPlayEnd(final String placementId) {
                    getAdListener().onAdComplete();
                }

                public void onInterstitialAdClicked(String placementId) {
                    getAdListener().onAdClick();

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_CLICK, FullScreenAdLoader.super.posId));
                }

                public void onInterstitialAdClosed(String placementId) {
                    getAdListener().onAdDismiss();

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_CLOSE, FullScreenAdLoader.super.posId));
                }

                public void onInterstitialAdLoadError(WindAdError error, String placementId) {
                    Log.e(GsonUtils.gsonString(AdError.build(platform, adType, error.getErrorCode(), error.getMessage())));
                    getAdListener().onAdLoadError(AdError.build(platform, adType, error.getErrorCode(), error.getMessage()));

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_RETURN_FAIL, FullScreenAdLoader.super.posId));
                }

                public void onInterstitialAdPlayError(WindAdError error, String placementId) {
                    Log.e(GsonUtils.gsonString(AdError.build(platform, adType, error.getErrorCode(), error.getMessage())));
                    onAdShowErrorSafety(AdError.build(platform, adType, error.getErrorCode(), error.getMessage()), platform, false);
                }
            };
            WindInterstitialAd ad = new WindInterstitialAd(context, request);
            listener.setAd(ad);
            ad.setWindInterstitialAdListener(listener);
            ad.loadAd();
        } else if (platform == AdPlatformEnum.PLATFORM_MINTEGRAL) {//没有全屏，代替使用激励
            MBRewardVideoHandler ad = new MBRewardVideoHandler(context, null, posId);
            ad.setRewardVideoListener(new RewardVideoListener() {
                public void onLoadSuccess(MBridgeIds ids) {

                }

                public void onVideoLoadSuccess(MBridgeIds ids) {
                    PoolMgr.getInstance().push(ad, config);

                    getAdListener().onAdLoad();

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_RETURN_SUCCESS, FullScreenAdLoader.super.posId));
                }

                public void onVideoLoadFail(MBridgeIds ids, String msg) {
                    Log.e(GsonUtils.gsonString(AdError.build(platform, adType, ErrorEnum.ERR_LOAD_FAILD.getId(), msg)));
                    getAdListener().onAdLoadError(AdError.build(platform, adType, ErrorEnum.ERR_LOAD_FAILD.getId(), msg));

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_RETURN_FAIL, FullScreenAdLoader.super.posId));
                }

                public void onShowFail(MBridgeIds ids, String msg) {
                    Log.e(GsonUtils.gsonString(AdError.build(platform, adType, ErrorEnum.ERR_SHOW_FAILD.getId(), msg)));
                    onAdShowErrorSafety(AdError.build(platform, adType, ErrorEnum.ERR_SHOW_FAILD.getId(), msg), platform, false);
                }

                public void onAdShow(MBridgeIds ids) {
                    onAdShowSafety();
                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_EXPOSURE, FullScreenAdLoader.super.posId));
                }

                public void onAdClose(MBridgeIds ids, RewardInfo rewardInfo) {
                    getAdListener().onAdDismiss();

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_CLOSE, FullScreenAdLoader.super.posId));
                }

                public void onVideoAdClicked(MBridgeIds ids) {
                    getAdListener().onAdClick();

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_CLICK, FullScreenAdLoader.super.posId));
                }

                public void onVideoComplete(MBridgeIds ids) {
                    getAdListener().onAdComplete();
                }

                public void onEndcardShow(MBridgeIds ids) {
                }
            });
            ad.load();
        }
    }

    protected void show(BaseAd ad) {
        AdPlaceWebConfigureVO config = ad.getConfig();
        AdPlatformEnum platform = config.getPlatform();
        String posId = config.getPositionId();

        if (platform == AdPlatformEnum.PLATFORM_CSJ) {//穿山甲
            TTFullScreenVideoAd adThird = (TTFullScreenVideoAd) ad.getAd();
            adThird.setFullScreenVideoAdInteractionListener(new TTFullScreenVideoAd.FullScreenVideoAdInteractionListener() {
                public void onAdShow() {
                    onAdShowSafety();

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_EXPOSURE, FullScreenAdLoader.super.posId));
                }

                public void onVideoComplete() {
                    getAdListener().onAdComplete();
                }

                public void onAdClose() {
                    getAdListener().onAdDismiss();

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_CLOSE, FullScreenAdLoader.super.posId));
                }

                public void onSkippedVideo() {

                }

                public void onAdVideoBarClick() {//广告下载bar点击
                    getAdListener().onAdClick();

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_CLICK, FullScreenAdLoader.super.posId));
                }
            });

            adThird.showFullScreenVideoAd(context, TTAdConstant.RitScenes.CUSTOMIZE_SCENES, null);
        } else if (platform == AdPlatformEnum.PLATFORM_YLH) {//优量汇(没有全屏广告，代替使用激励广告。即在聚合平台全屏广告位中优量汇中直接使用激励的广告位ID，但应该有重复绑定的错误)
            RewardVideoADListener listener = new RewardVideoADListener() {
                private boolean hasPop = false;

                public void onVideoCached() {

                }

                public void onADLoad() {
                    getAd().showAD(context);
                    getAdListener().onAdLoad();
                    hasPop = true;

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_RETURN_SUCCESS, FullScreenAdLoader.super.posId));
                }

                public void onADShow() {
                    onAdShowSafety();
                }

                public void onADExpose() {
                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_EXPOSURE, FullScreenAdLoader.super.posId));
                }

                public void onReward(Map<String, Object> map) {

                }

                public void onVideoComplete() {
                    getAdListener().onAdComplete();
                }

                public void onADClose() {
                    getAdListener().onAdDismiss();

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_CLOSE, FullScreenAdLoader.super.posId));
                }

                public void onADClick() {
                    getAdListener().onAdClick();

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_CLICK, FullScreenAdLoader.super.posId));
                }

                public void onError(com.qq.e.comm.util.AdError error) {//加载错误或播放错误
                    Log.e(GsonUtils.gsonString(AdError.build(platform, adType, error.getErrorCode(), error.getErrorMsg())));
                    if (!hasPop) {
                        getAdListener().onAdLoadError(AdError.build(platform, adType, error.getErrorCode(), error.getErrorMsg()));
                    } else {
                        onAdShowErrorSafety(AdError.build(platform, adType, error.getErrorCode(), error.getErrorMsg()), platform, false);
                    }

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_RETURN_FAIL, FullScreenAdLoader.super.posId));
                }
            };
            RewardVideoAD adYlh = new RewardVideoAD(context, posId, listener, true);
            listener.setAd(adYlh);
            adYlh.loadAD();
        } else if (platform == AdPlatformEnum.PLATFORM_KS) {//快手联盟
            KsFullScreenVideoAd adThird = (KsFullScreenVideoAd) ad.getAd();
            KsVideoPlayConfig videoPlayConfig = new KsVideoPlayConfig.Builder()
                    .showLandscape(orientation == LANDSCAPE)//方向
                    .videoSoundEnable(true)//声音策略
                    .build();
            adThird.setFullScreenVideoAdInteractionListener(new KsFullScreenVideoAd.FullScreenVideoAdInteractionListener() {
                public void onVideoPlayStart() {
                    onAdShowSafety();

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_EXPOSURE, FullScreenAdLoader.super.posId));
                }

                public void onVideoPlayEnd() {
                    getAdListener().onAdComplete();
                }

                public void onPageDismiss() {
                    getAdListener().onAdDismiss();

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_CLOSE, FullScreenAdLoader.super.posId));
                }

                public void onSkippedVideo() {

                }

                public void onAdClicked() {
                    getAdListener().onAdClick();

                    ApiServiceImpl.addTrack(UserBehaviorAddDTO.build(config, AdEventSign.AD_CLICK, FullScreenAdLoader.super.posId));
                }

                public void onVideoPlayError(int code, int extra) {
                    Log.e(GsonUtils.gsonString(AdError.build(platform, adType, code, String.valueOf(extra))));
                    onAdShowErrorSafety(AdError.build(platform, adType, code, String.valueOf(extra)), platform, false);
                }
            });
            adThird.showFullScreenVideoAd(context, videoPlayConfig);
        } else if (platform == AdPlatformEnum.PLATFORM_SIGMOB) {
            WindInterstitialAd adThird = (WindInterstitialAd) ad.getAd();
            if (adThird.isReady()) {
                adThird.show(context, null);
            } else {
                Log.e(GsonUtils.gsonString(ErrorEnum.ERR_NOT_READY.rsp(platform, adType)));
                onAdShowErrorSafety(ErrorEnum.ERR_NOT_READY.rsp(platform, adType), platform, true);
            }
        } else if (platform == AdPlatformEnum.PLATFORM_MINTEGRAL) {
            MBRewardVideoHandler adThird = (MBRewardVideoHandler) ad.getAd();
            if (adThird.isReady()) {
                adThird.show();
            } else {
                Log.e(GsonUtils.gsonString(ErrorEnum.ERR_NOT_READY.rsp(platform, adType)));
                onAdShowErrorSafety(ErrorEnum.ERR_NOT_READY.rsp(platform, adType), platform, true);
            }
        }
    }
}
